package toy.keli.edic.ui.bookmark.components

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.ExperimentalUnitApi
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.res.ResourcesCompat
import com.google.accompanist.glide.rememberGlidePainter
import toy.keli.edic.R
import toy.keli.edic.data.config.BookConf
import toy.keli.edic.ui.bookmark.BookMarkEvent
import toy.keli.edic.ui.bookmark.data.BookItem
import toy.keli.edic.ui.bookmark.data.BookItemType
import toy.keli.edic.ui.bookmark.data.BookMark.Companion.bookItems
import toy.keli.edic.ui.bookmark.data.BookMark.Companion.clickModel
import toy.keli.edic.ui.bookmark.data.BookMark.Companion.pid
import toy.keli.edic.ui.bookmark.data.BookMark.clickModelItem
import toy.keli.edic.ui.bookmark.data.VirtualCommonItem
import toy.keli.edic.ui.main.components.Display.mt
import toy.keli.edic.ui.main.components.ProgressDialog
import toy.keli.edic.ui.main.extend.MainRun
import toy.keli.edic.ui.main.extend.bgRun
import toy.keli.edic.util.ActivityRun
import toy.keli.edic.view.MPopMenu
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import toy.keli.edic.ui.home.HomeEvents

@OptIn(ExperimentalFoundationApi::class, ExperimentalUnitApi::class)
@Composable
@Preview
fun BookGrid() {
    val cells = if(ActivityRun.isHorizontalScreens()) GridCells.Adaptive(150.dp) else  GridCells.Fixed(4)
    val vScsroll = rememberLazyGridState();
    HomeEvents.status.openDrowUp = vScsroll.firstVisibleItemIndex ==0
    HomeEvents.status.enableDrowDown = remember(vScsroll) {
        derivedStateOf {
            // 获取列表布局信息
            val layoutInfo = vScsroll.layoutInfo
            // 总项数
            val totalItemsCount = layoutInfo.totalItemsCount
            if (totalItemsCount == 0) {
                // 没有数据时视为“已在结尾”
                return@derivedStateOf true
            }
            // 最后一个可见项的索引
            val lastVisibleItemIndex = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
            // 当最后一个可见项索引 >= 总项数 - 1 时，视为到达结尾
            // 可根据需求调整偏移量（如 -3 表示提前3项判断为接近结尾）
            lastVisibleItemIndex >= totalItemsCount - 1
        }
    }.value

    LazyVerticalGrid (
        state = vScsroll,
        columns = cells,
        modifier = Modifier
            .padding(horizontal = 16.dp)
    ){
        itemsIndexed(bookItems.filter{it.type == BookItemType.category}) { _, item ->
            Item2(item)
        }
        if(pid==0) {
            itemsIndexed(VirtualCommonItem.all) { _, item ->
                Item2(item)
                if (pid == item.id) {
                    BookMarkEvent.onCommonItemClick(item)
                }
            }
        }
        itemsIndexed(bookItems.filter{it.type == BookItemType.article}) { _, item ->
            Box {
                Item2(item)
                //初始化mp3文件的进度条
                if (!item.inited ) {
//                    Text(
//                            item.initStatusText, color = Color.Red, modifier = Modifier.align(Alignment.TopCenter)
//                            .padding(top = 10.dp)
//                    )

                    if (ProgressDialog.size.value>0 && BookMarkEvent.openItem!=null && BookMarkEvent.openItem!! == item) {
                        Text(text = "" + ProgressDialog.pos.value + "/" + ProgressDialog.size.value,
                            fontSize = 6.sp,
                            textAlign = TextAlign.Center
                        )
                        LinearProgressIndicator(
                            //0.0表示没有进度，1.0表示已完成进度
                            progress = ProgressDialog.progress.value,
                            modifier = Modifier.padding(10.dp).align(Alignment.BottomCenter),
                            color = Color.Green,
//                            backgroundColor = Color.Gray
                        )
                    }
                }
            }
        }
        itemsIndexed(bookItems.filter{it.type == BookItemType.word}) { index, item ->
            Item2(item)
            item.index = index
        }
    }
}

@OptIn(ExperimentalFoundationApi::class, ExperimentalUnitApi::class)
@Composable
fun Item2(item: Any){
        val isBi = item::class.java.equals(BookItem::class.java)
        val itemBi = if(isBi) item as BookItem else null
        val menu = if(isBi) MPopMenu.categoryEditMenu(item as BookItem) else null
        val bgc = if(
            (BookMarkEvent.bookId>0 && isBi && itemBi!!.type ==BookItemType.article && itemBi!!.id == BookMarkEvent.bookId) ||
            (BookMarkEvent.dirId>0 && isBi && itemBi!!.type ==BookItemType.category && itemBi!!.id == BookMarkEvent.dirId)
        ){
            MaterialTheme.colorScheme.secondary
        }else MaterialTheme.colorScheme.background

        Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.padding(5.dp)
                    .wrapContentHeight()
                    .combinedClickable(
                        onClick = {
                            if(isBi) {
                                BookMarkEvent.ItemOnClick(itemBi!!)
                            }else{
                                BookMarkEvent.onCommonItemClick(item as VirtualCommonItem)
                            }
                        },
                        onLongClick = {
                            if(menu!=null) {
                                BookMarkEvent.ItemonLongClick(menu)
                            }
                        }
                    )
                    .background(bgc)
            ) {
                val ico = if (isBi) itemBi!!.ico else (item as VirtualCommonItem).ico
                val name = if (isBi) itemBi!!.name else mt((item as VirtualCommonItem).name)
                Box {
                    if (ico > 0) {
                        val ct = LocalContext.current
                        if (isBi && itemBi!!.hasCustomIco()) {
                            val bitmapState = remember(itemBi?.id) { mutableStateOf<Bitmap?>(null) }
                            // 2. 只在项变化时触发一次异步加载
                            LaunchedEffect(itemBi?.id) {
                                withContext(Dispatchers.IO) {
//                                val t =(itemBi?.id!! -88)*10000
//                                delay(t.toLong()) // 可选：添加短暂延迟避免UI闪烁
                                  bitmapState.value = itemBi!!.customIco()
                                }
                            }

                            bitmapState.value?.let { bitmap ->
                                Image(
                                    painter = rememberGlidePainter(request = bitmap),
                                    contentDescription = name,
                                    modifier = Modifier.size(70.dp)
                                )
                            }
                        } else {
                            Image(
                                painter = painterResource(ico),
                                name,
                                modifier = Modifier
                                    .size(70.dp)
                            )
                        }

                        // Spacer(Modifier.height(5.dp))
                    }
                    if (isBi) {
                        if (clickModel == clickModelItem.isSelect) {
                            RadioButton(selected = itemBi!!.isSelect, onClick = {
                                itemBi!!.changeSelecte()
                            }, modifier = Modifier
                                .padding(0.dp)
                                .size(20.dp)
                            )
                        }
                    }
                }
                if(isBi && itemBi!!.type == BookItemType.word)
                {
                    Text(itemBi!!.name, modifier = Modifier)
                    Spacer(Modifier.width(5.dp))
                    Text(itemBi!!.content!!)
                    Spacer(modifier = Modifier.weight(1f))
                    IconButton(onClick = {
                        itemBi!!.delete()
                        BookMarkEvent.Run.upBookItems()
                    }, modifier = Modifier.weight(.5f)) {
                        Icon(
                            painter = painterResource(id = R.drawable.delete),
                            contentDescription = null,
                            tint = Color.Red
                        )
                    }
                }else {
                    Text(mt(name.replace(Regex("\\.\\w+$"),"")), fontSize = 10.sp)
//                    Spacer(modifier = Modifier.weight(1f))
//                    Text(
//                        item.upTime ?: "",
//                        color = Color.Gray,
//                        fontSize = TextUnit(10f, TextUnitType.Sp)
//                    )
                }
                if(menu!=null) {
                    menu.add()
                }
        }
}